import subscribe from '@/utils/subscribe.js'

let socket = null;
if (window.WebSocket) {
  socket = new window.WebSocket("ws://localhost:9090/chat");
}
socket.onopen = function (e) {
  console.log("建立连接");
  subscribe.emits("WEBSOCKET:CONNECTION")
};


socket.onmessage = function (e) {
  let item = JSON.parse(e.data);
  //"WEBSOCKET:CHITCHAT"
  if (item.type === "CHITCHAT") { //一对一聊天
    subscribe.emits("WEBSOCKET:CHITCHAT",item)
  }
  console.log("消息接收",e.data);
}

socket.onclose = function (e) {
  console.log("socket 关闭");
}

socket.onerror = function (e) {
  console.log(" socket 错误");
}


//---------------------------------------
subscribe.on("WEBSOCKET:SEND", (msg) => {
  socket.send(JSON.stringify(msg))
})

export default socket;

